package cc.vicp.djx314.starfood.web.user;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.support.ServletContextResource;
import org.springframework.web.servlet.ModelAndView;

import cc.vicp.djx314.starfood.domain.account.User;
import cc.vicp.djx314.starfood.service.account.AccountService;
import cc.vicp.djx314.starfood.service.account.UserInfoService;
import cc.vicp.djx314.starfood.util.DealResult;
import cc.vicp.djx314.starfood.util.time.DateEditor;
import cc.vicp.djx314.starfood.web.validator.UserValidator;

@Controller
public class UserRegisterController {
	public static final Logger logger = LoggerFactory.getLogger(UserRegisterController.class);

	@Autowired
	public AccountService accountService;

	@Autowired
	public UserInfoService userInfoService;

	@Autowired
	public UserValidator userValidator;

	@Autowired
	public DealResult dealResult;

	@RequestMapping(value = "/register/user", method = RequestMethod.GET)
	public String validationAndRegisterUserPage() {
		return "customer/user/register";
	}

	@InitBinder
	protected void initBinder(HttpServletRequest request,
			ServletRequestDataBinder binder) throws Exception {
		//对于需要转换为Date类型的属性，使用DateEditor进行处理
		binder.registerCustomEditor(Date.class, new DateEditor());
	}

	//注册用户(经过各项逻辑判断再决定注册与否,不成功的返回错误信息)
	@RequestMapping(value = "/register/user", method = RequestMethod.POST)
	public ModelAndView validationAndRegisterUser(@ModelAttribute("user") @Valid User user,
			BindingResult result,
			@RequestParam(defaultValue = "default.jpg", value = "fileName") String fileName,
			HttpServletRequest request, HttpSession session) {
		ModelAndView model = new ModelAndView("jsontournamenttemplate");
		if (result.hasErrors()) {
			//System.out.println(user.getBirthday());
			Map<String, String> errorsMap = dealResult.errorsToMap(result);
			model.addObject("errors", errorsMap);
			model.addObject("success", false);
			//System.out.println("11111111111111111");
		} else {
			userValidator.validate(user, result);
			if (result.hasErrors()) {
				Map<String, String> errorsMap = dealResult.errorsToMap(result);
				model.addObject("errors", errorsMap);
				model.addObject("success", false);
				//System.out.println("11111111111111111");
			} else {
				boolean isSuccess = false;
				try {
					ServletContext context = request.getSession().getServletContext();
					Resource resource = new ServletContextResource(context, "/img/headtemp/" + fileName);
					File headImgFile = resource.getFile();
					byte[] headImg = FileCopyUtils.copyToByteArray(headImgFile);
					userInfoService.createUser(user, headImg);
					session.setAttribute("registeredUser", user);
					isSuccess = true;
					//System.out.println("11111111111111111");
				} catch (IOException e1) {
					logger.info("头像文件找不到", e1);
					model.addObject("fileNotFound", true);
					isSuccess = false;
				} catch (Exception e2) {
					logger.error("创建用户发生未知错误", e2);
					isSuccess = false;
				}
				model.addObject("success", isSuccess);
			}
		}
		return model;
	}

	//判断用户名是否存在
	@RequestMapping(value = "/register/accountexists/{name}", method = RequestMethod.GET)
	public ModelAndView isAccountNameExists(@PathVariable("name") String name) throws UnsupportedEncodingException {
		name = new String(name.getBytes("iso-8859-1"), "UTF-8");
		//System.out.println(name);
		boolean isAccountNameExists = true;
		try {
			isAccountNameExists = accountService.isAccountNameExists(name);
		} catch (Exception e) {
			logger.info("数据库操作出现未知错误", e);
		}
		ModelAndView model = new ModelAndView("jsontournamenttemplate");
		model.addObject("success", true);
		model.addObject("isExists", isAccountNameExists);
		return model;
	}

	@RequestMapping(value = "/register/usernicknameexists/{name}", method = RequestMethod.GET)
	public ModelAndView isUserNickNameExists(@PathVariable(value = "name") String name) throws UnsupportedEncodingException {
		name = new String(name.getBytes("iso-8859-1"), "UTF-8");
		//System.out.println(name);
		boolean isExists = true;
		try {
			isExists = userInfoService.isNickNameExists(name);
		} catch (Exception e) {
			logger.info("数据库操作出现未知错误", e);
		}
		ModelAndView model = new ModelAndView("jsontournamenttemplate");
		model.addObject("success", true);
		model.addObject("isExists", isExists);
		return model;
	}

	@RequestMapping(value = "/register/success", method = RequestMethod.GET)
	public String registerSuccessInfo() {
		return "customer/user/registersuccess";
	}
}